import RouteGenerator, updateDB, psycopg2, datetime, random, PEIR, sys

username = ''
password = ''
dbname   = 'cyclesense'
host     = 'localhost'

"*** set permissions ***"
def setConfig():
    global username, password, dbname, host
    username = RouteGenerator.username
    password = RouteGenerator.password
    dbname = RouteGenerator.dbname
    host = RouteGenerator.host

"*** takes a random hour and returns a random time nearby ***"
def randomTime(hour):
    minutes = int(random.gauss(0,60) + .5)
    while minutes >= 60:
        hour = hour + 1
        minutes = minutes - 60
    while minutes < 0:
        hour = hour - 1
        minutes = minutes + 60
    return hour, minutes

"***parses time returned by PEIR interface, will return in some format like***"
def parseTime(time):
    time = time.split(' ')
    time2 = time[1].split(':')
    newHours = time2[0]
    newHours = newHours.lstrip('0')
    newMinutes = time2[1]
    newMinutes = newMinutes.lstrip('0')
    if newMinutes == '':
        newMinute = '0'
    return newHours, newMinutes

"*** main function ***"
def generateBotTrace(botName):
    global username, password, dbname, host
    "*** finding the current year,month,day (these should stay the same for a day's traces ***"
    curYear = datetime.datetime.now().year
    curMonth = datetime.datetime.now().month
    curDay = datetime.datetime.now().day
    
    if username == '' or password == '' or dbname == '' or host == '':
        RouteGenerator.setConfig()
        setConfig()
    extraLocations = 0 
    conn = psycopg2.connect("dbname = '" + dbname + "' host = '" + host + "' user = " + username + " password = " + password)
    cur = conn.cursor()
    query = "SELECT homecoordinates,workcoordinates,otherlocations FROM peirbots WHERE name = '" + botName + "'"
    cur.execute(query)
    allCoordinatePairs = cur.fetchall()
    if len(allCoordinatePairs) == 0:
        print "no PEIRbot of that name!"
        return
    if len(allCoordinatePairs) > 1:
        print "Two PEIRbots with same name in the database, defaulting to first PEIRbot"
        
    "*** parsing home and work coordinates, stored inside latHome,lonHome,latWork,lonWork***"
    allCoordinatePairs = allCoordinatePairs[0]
    homeCoordinates = allCoordinatePairs[0]
    latHome,lonHome = homeCoordinates.split(',')
    latHome = eval(latHome)
    lonHome = eval(lonHome)
    workCoordinates = allCoordinatePairs[1]
    latWork, lonWork = workCoordinates.split(',')
    latWork = eval(latWork)
    lonWork = eval(lonWork)
    if allCoordinatePairs[2] != None:
        locationsCoordinates = allCoordinatePairs[2].split(':')
        extraLocations = len(locationsCoordinates)
    "*** first generate path for work in the morning,  assuming heading to work sometime around 8 am ***"
    morningHour, morningMinutes = randomTime(8)
    startDateTime = datetime.datetime(curYear,curMonth,curDay,morningHour,morningMinutes)
    a, finaltime = PEIR.peir_interface(1, latHome, lonHome, latWork, lonWork, start = startDateTime)
    newHours, newMinutes = parseTime(finaltime)
    "*** find time to leave work so that we can generate random trips in the middle and then go home ***"
    afternoonHour, afternoonMinutes = randomTime(17)
    endWorkDateTime = datetime.datetime(curYear,curMonth,curDay,afternoonHour,afternoonMinutes)
    newDateTime = datetime.datetime(curYear,curMonth,curDay,eval(newHours),eval(newMinutes))
    tempLat = latWork
    tempLon = lonWork #this is where we are now
    "*** generate random paths in middle of the day ***"
    
    while 1 and extraLocations != 0:
        #print newDateTime.strftime("%Y-%m-%d %H:%M:%S")
        randomTimeDelta = int(random.gauss(2400, 600) + .5) #this is in seconds..so want it to be 40 minutes with 10 min deviation
        newDateTime = newDateTime + datetime.timedelta(0,randomTimeDelta)
        deltaValue = endWorkDateTime - newDateTime
        if deltaValue.days == -1:
            break
        "*** 30% of going other places besides work ***"
        if random.randint(1,10) >= 8: 
            counter = random.randint(0,extraLocations-1)
            coordinatesToGo = locationsCoordinates[counter]
            newLat, newLon = coordinatesToGo.split(',')
            newLat = eval(newLat)
            newLon = eval(newLon)
            if newLat == tempLat and newLon == tempLon:
                print "same location hit"
                continue #ignore if we're at the same place
            "*** random trip ***"
            "going on a trip to newLat,newLon"
            a, finaltime = PEIR.peir_interface(1, tempLat, tempLon, newLat, newLon, start = newDateTime)
            tempLat = newLat
            tempLon = newLon
            newHours,newMinutes = parseTime(finaltime)
            "*** reset the new time (how long does the person stay at the nonwork place ***"
            randomTimeDelta = int(random.gauss(2400, 600) + .5) #this is in seconds..so want it to be 40 minutes with 10 min deviation
            newDateTime = datetime.datetime(curYear,curMonth,curDay,eval(newHours),eval(newMinutes))
            newDateTime = newDateTime + datetime.timedelta(0,randomTimeDelta)
            deltaValue = endWorkDateTime - newDateTime
            if deltaValue.days == -1:
                "*** go home if time is up...otherwise, back to work***"
                break
            a, finaltime = PEIR.peir_interface(1, tempLat, tempLon, latWork, lonWork, start = newDateTime)
            tempLat = latWork
            tempLon = lonWork
            newHours,newMinutes = parseTime(finaltime)
            print newHours,newMinutes
            newDateTime = datetime.datetime(curYear,curMonth,curDay,eval(newHours),eval(newMinutes))

    #newSeconds = finaltime2[2]
    #print newHours, newMinutes, newSeconds
    "*** go straight home after getting back to work? e.g. has time ran out"
    goStraightHome = False
    deltaValue = endWorkDateTime - newDateTime
    if deltaValue.days == -1:
        goStraightHome = True
    
    #afternoonHour, afternoonMinutes = randomTime(17)
    #endWorkDateTime = datetime.datetime(curYear,curMonth,curDay,eval(newHours),eval(newMinutes))
    "*** the return home***"
    if goStraightHome == True:
        a, finaltime = PEIR.peir_interface(1, tempLat, tempLon, latHome, lonHome, start = newDateTime)
    else:
        a, finaltime = PEIR.peir_interface(1, tempLat, tempLon, latHome, lonHome, start = endWorkDateTime)
    #print finaltime
if __name__ == "__main__":
    if len(sys.argv) >= 2:
        if sys.argv[1] == '-n':
            if len(sys.argv) == 3:
                generateBotTrace(sys.argv[2])
            else:
                print "BAD FORMAT \n"
                print "FORMAT: -n [name of PEIRbot]"
        else:
            print "BAD FORMAT \n"
            print "options: \n"
            print "-n : name \n"
    #generateBotTrace('Poo Face')
    else:
        print "INCORRECT FORMAT"
        print "BAD FORMAT \n"
        print "options: \n"
        print "-n : name \n"